package com.zcoj.api.handler;

import com.zcoj.api.exception.BizException;
import com.zcoj.api.exception.ContestOnGoingException;
import com.zcoj.core.model.ApiResponse;
import io.jsonwebtoken.ExpiredJwtException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;


/**
 * @method: [自定义异常处理]
 * @param: 
 * @returns: 
 * @description:        
 * @author: chen.bin
 * @version: 1.0.0
 * @date 2023/3/5 10:21
 **/
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理自定义的业务异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public ApiResponse bizExceptionHandler(HttpServletRequest req, BizException e){
        logger.error("发生业务异常！原因是：{}",e.getErrorMsg());
        return ApiResponse.failed("业务异常");
    }

    @ExceptionHandler(value = ContestOnGoingException.class)
    @ResponseBody
    public ApiResponse contestOnGoingExceptionHandler(HttpServletRequest req, ContestOnGoingException e){
        logger.error("发生业务异常！原因是：{}",e.getErrorMsg());
        return ApiResponse.failed("比赛中禁止访问！");
    }

    /**
     * 处理空指针的异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value =NullPointerException.class)
    @ResponseBody
    public ApiResponse exceptionHandler(HttpServletRequest req, NullPointerException e){
        logger.error("发生空指针异常！原因是:",e);
        return ApiResponse.failed("空指针异常");
    }

    /**
     * 处理其他异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value =Exception.class)
    @ResponseBody
    public ApiResponse exceptionHandler(HttpServletRequest req, Exception e){
        logger.error("未知异常！原因是:",e);
        return ApiResponse.failed("系统异常");
    }

    @ExceptionHandler(value = ExpiredJwtException.class)
    @ResponseBody
    public ApiResponse exceptionHandler(HttpServletRequest req, ExpiredJwtException e){
        logger.error("未知异常！原因是:",e);
        return ApiResponse.failed("token异常");
    }

    @ExceptionHandler(AuthenticationException.class)
    @ResponseBody
    public ApiResponse handleAuthenticationException(AuthenticationException e) {
        logger.error("认证异常！", e);
        return ApiResponse.failed("认证失败，请重新登录！");
    }

    @ExceptionHandler(AccessDeniedException.class)
    @ResponseBody
    public ApiResponse handleAccessDeniedException(AccessDeniedException e) {
        logger.error("权限异常！", e);
        return ApiResponse.failed("无权访问该资源！");
    }

}
